
def code_checksum(code, ean = False, stickybit = False, modulo = 10):

    code = str(code)

    weights = [3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
    if stickybit:
        weights = map(lambda x: 1 if x == 1 else 4, weights)

    sum = 0
    startpos = len(weights) - len(code)

    for i in range(0, len(code)):
        sum += int(code[i]) * weights[startpos + i]

    modsum = sum % modulo

    if ean:
        digit = 10 - modsum
        if digit == 10:
            digit = 0
    else:
        digit = str(modsum)
        digit = digit.rjust(2, '0')

    return str(digit)


def generate_stickybit(codenum):

    codenum = str(codenum).rjust(11, '0')

    if not codenum or len(codenum) > 11:
        raise

    sb_checksum = code_checksum(codenum, stickybit = True, modulo = 90)
    front_num = sb_checksum[1:]
    back_num  = sb_checksum[:1]

    ean_checksum = code_checksum(front_num + codenum, ean = True)
    if ean_checksum == back_num:
        back_num = str(int(back_num) + 1)

    return front_num + codenum + back_num


def valid_stickybit(code):

    code = str(code)
    if not code or len(code) != 13:
        return False

    try:
        meat = code[1:-1]
        realcode = generate_stickybit(meat)
        if realcode == code:
            return True
    except:
        pass

    return False

"""

print valid_stickybit(6214788223642)

"""
